package org.framework.server.util.dao.sql.support;


public class QueryBuilder {
	
	private String sql;
	
	private String countSql;
	
	private Condition condition;
	
	private Profile profile;
	
	private Object[] sqlParams;
	
	public QueryBuilder(String sql) {
		this(sql, null, null, null);
	}
	
	public QueryBuilder(String sql, String countSql) {
		this(sql, countSql, null, null);
	}
	
	public QueryBuilder(String sql, Condition condition) {
		this(sql, null, condition, null);
	}
	
	public QueryBuilder(String sql, String countSql, Condition condition) {
		this(sql, countSql, condition, null);
	}
	
	public QueryBuilder(String sql, Condition condition, Profile profile) {
		this(sql, null, condition, profile);
	}
	
	public QueryBuilder(String sql, String countSql, Condition condition, Profile profile) {
		this.sql = sql;
		this.countSql = countSql==null?sql.replaceFirst("select(.*)from", "select count(0) from") : countSql;
		this.condition = condition;
		this.profile = profile;
		this.sqlParams = this.condition.getValues();
	}
	
	
	public String getSql() {
		if(this.condition != null)
			this.sql += " " + this.condition.toSql();
		if(this.profile != null)
			this.sql += " " + this.profile.toSortSql();
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public String getCountSql() {
		if(this.condition != null)
			this.countSql += " " + this.condition.toSql();
		return countSql;
	}

	public void setCountSql(String countSql) {
		this.countSql = countSql;
	}

	public Condition getCondition() {
		return condition;
	}

	public void setCondition(Condition condition) {
		this.condition = condition;
	}

	public Profile getProfile() {
		return profile;
	}

	public void setProfile(Profile profile) {
		this.profile = profile;
	}

	public Object[] getSqlParams() {
		return sqlParams;
	}
	
	public void setSqlParams(Object[] sqlParams) {
		this.sqlParams = sqlParams;
	}
	
	public static void main(String[] args) {
		System.out.println("select * from tbl_user".replaceFirst("select(.*)from", "select count(0) from"));
	}
	
}
